package org.linlinjava.litemall.core.systemConfig;

import org.linlinjava.litemall.db.domain.LitemallAddress;
import org.linlinjava.litemall.db.domain.LitemallRegion;
import org.linlinjava.litemall.db.service.LitemallRegionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.*;

/**
 * @author zhy
 * @date 2019-01-17 23:07
 **/
@Component
public class GetRegionService {
	@Autowired
	private LitemallRegionService regionService;

	/**
	 * 拒绝策略，都满的情况下把被拒绝的线程重新执行
	 */
	private ThreadPoolExecutor executorService = new ThreadPoolExecutor(3, 6, 1000, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(20), new ThreadPoolExecutor.CallerRunsPolicy());

	protected String getdetailedAddress(LitemallAddress litemallAddress) {
		List<LitemallRegion> regionList = getLitemallRegions();
		Integer provinceId = litemallAddress.getProvinceId();
		Integer cityId = litemallAddress.getCityId();
		Integer areaId = litemallAddress.getAreaId();

		FutureTask<String> provinceNameCallableTask = new FutureTask<>(() -> regionList.stream().filter(region -> region.getId().equals(provinceId)).findAny().orElse(null).getName());
		FutureTask<String> cityNameCallableTask = new FutureTask<>(() -> regionList.stream().filter(region -> region.getId().equals(cityId)).findAny().orElse(null).getName());
		FutureTask<String> areaNameCallableTask = new FutureTask<>(() -> regionList.stream().filter(region -> region.getId().equals(areaId)).findAny().orElse(null).getName());
		executorService.submit(provinceNameCallableTask);
		executorService.submit(cityNameCallableTask);
		executorService.submit(areaNameCallableTask);
		String fullRegion = "";
		try {
			String provinceName = provinceNameCallableTask.get();
			String cityName = cityNameCallableTask.get();
			String areaName = areaNameCallableTask.get();
			fullRegion = provinceName + " " + cityName + " " + areaName;
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return fullRegion + " " + litemallAddress.getAddress();
	}

	private static List<LitemallRegion> litemallRegions;

	protected List<LitemallRegion> getLitemallRegions() {
		if(litemallRegions==null){
			createRegion();
		}
		return litemallRegions;
	}

	private synchronized void createRegion(){
		if (litemallRegions == null) {
			litemallRegions = regionService.getAll();
		}
	}


}
